package tema4;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name="NumerosPrimosServlet", urlPatterns={"/tema4/numerosPrimos"})
public class NumerosPrimosServlet extends HttpServlet {
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        
        int min = Integer.parseInt(request.getParameter("minimo"));
        int max = Integer.parseInt(request.getParameter("maximo"));

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Numeros Primos comprendidos entre: "+min+" y "+max+"</title>");
            out.println("<link rel=\"stylesheet\" title=\"standar\" type=\"text/css\" href=\"/EjemploBasicoJavaEE/standar.css\">");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Numeros Primos comprendidos entre: "+min+" y "+max+":</h1>");
            
            if(min < 0 || min > max || (min==0 && max==0))
                out.println("<h2>Has insertado unos valores absurdos!!</h2>");
            else{
                Integer[] primos = calculaPrimosComprendidosEntre(min,max);
                out.println("<ul>");
                for (int primo : primos)
                    out.println("<li>" + primo + "</li>");
                out.println("</ul>");
            }
            out.println("<h4>¡Eso es todo!</h4>");
            out.println("</body>");
            out.println("</html>");            
        } finally { 
            out.close();
        }
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    private Integer[] calculaPrimosComprendidosEntre(int min, int max) {
        List<Integer> primos = new ArrayList<Integer>();
        int base = 2;
        int resto = 1;
        if(min == 0)
            min = 1;
        while(min <= max){
            while(min>base && resto!=0){
                resto = min%base;
                base++;
            }
            if(resto != 0)
                primos.add(min);
            min++;
            base = 2;
            resto = 1;
        }            
        return primos.toArray(new Integer[0]);
    }

}
